# -*- coding: utf-8 -*-
'''
Created on 2013-4-11

@author: cl.lam
'''
from datetime import datetime as dt
from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_

from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, activetab, \
    allPermission, mypaginate
from sys2do.constant import TAB_BASIC, MSG_NOT_ENOUGH_PARAMS, MESSAGE_ERROR, \
    ACTIVE, MSG_NOT_ALL_PARAMS_OK, MSG_SAVE_SUCC, MESSAGE_INFO, MSG_SERVER_ERROR, \
    MSG_UPDATE_SUCC, MSG_RECORD_NOT_EXIST, INACTIVE, MSG_DELETE_SUCC, \
    MSG_SAME_NAME_RECORD_EXIST
from sys2do.util.logic_helper import getCurrentShopProfile, getCurrentUserID
from sys2do.util.common import _g, _gld
from sys2do.util.wt_helper import MyDateField
from sys2do.model import db, qry, ProductType, ProductShap, ProductSeries, User
from sys2do.model.system import SysLog



__all__ = ['bpMas']

bpMas = Blueprint( 'bpMas', __name__ )

class MasterView( BasicView ):

    template_folder = "mas"

    @templated( "index.html" )
    @activetab( TAB_BASIC )
    @loginRequired
    def index( self ):
        spobj = getCurrentShopProfile()

        return {'canUpdateProduct' : spobj.canUpdateProduct == 0, }


    @templated( 'pdtattr.html' )
    @allPermission( ['MASTER_EDIT'] )
    def pdtattr( self ):
        return {}


    @templated( 'masindex.html' )
    @mypaginate( 'result' )
    @allPermission( ['MASTER_EDIT'] )
    @loginRequired
    def masindex( self ):
        t = _g( 't' )
        if not t or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ENOUGH_PARAMS, MESSAGE_ERROR )
            return redirect( url_for( '.view' ) )

        formClz, label = SrhForm, u''
        if t == 'PT':
            obj, label = ProductType, u'商品类型'
        elif t == 'PS':
            obj, label = ProductShap, u'商品形状'
        elif t == 'PSR':
            obj, label = ProductSeries, u'商品系列'

        if request.method == 'POST':
            form = formClz( request.form )
            session[url_for( '.view', action = 'masindex' )] = form
        else:
            form = session.get( url_for( '.view', action = 'masindex' ), formClz( request.form ) )
        form.t.data = t
        form.url = url_for( '.view', action = 'masindex' )

        cds = [obj.active == ACTIVE, obj.createById == User.id, ]

        if form.no.data : cds.append( obj.no.like( '%%%s%%' % form.no.data ) )
        if form.name.data : cds.append( obj.name.like( '%%%s%%' % form.name.data ) )
        if form.createTimeFrom.data : cds.append( obj.createTime > form.createTimeFrom.data )
        if form.createTimeTo.data : cds.append( obj.createTime < form.createTimeTo.data )
        result = qry( obj, User ).filter( and_( *cds ) ).order_by( obj.name )

        return {'form' : form, 'result' : result, 't' : t, 'label' : label}


    @templated( 'add.html' )
    @allPermission( ['MASTER_CREATE'] )
    @loginRequired
    def add( self ):
        t = _g( 't' )
        if not t or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ENOUGH_PARAMS, MESSAGE_ERROR )
            return redirect( url_for( '.view', action = 'pdtattr' ) )

        formClz, label = AddForm, u''
        if t == 'PT':
            label = u'商品类型'
        elif t == 'PS':
            label = u'商品形状'
        elif t == 'PSR':
            label = u'商品系列'

        form = formClz( request.form )
        return {'form' : form, 'label' : label, 't' : t }




    def saveNew( self ):
        params = _gld( 'name', 'remark' )
        t = _g( 't' )
        if not t or not params['name'] or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            if t :
                return redirect( url_for( '.view', action = 'pdtattr', t = t ) )
            else:
                return redirect( url_for( '.view', action = 'masindex' ) )

        clz, label = SrhForm, u''
        if t == 'PT':
            clz, label = ProductType, u'商品类型'
        elif t == 'PS':
            clz, label = ProductShap, u'商品形状'
        elif t == 'PSR':
            clz, label = ProductSeries, u'商品系列'

        if self._isDuplicate( clz, params['name'] ) : return redirect( url_for( '.view', action = 'add', t = t ) )

        try:
            db.add( clz.create( params ) )
            db.commit()
            flash( MSG_SAVE_SUCC, MESSAGE_INFO )
        except:
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )

        return redirect( url_for( '.view', action = 'masindex', t = t ) )


    @templated( 'update.html' )
    @allPermission( ['MASTER_EDIT'] )
    @loginRequired
    def update( self ):
        oid, t = _g( 'id' ), _g( 't' )
        if not oid or not t or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            if t :
                return redirect( url_for( '.view', action = 'pdtattr', t = t ) )
            else:
                return redirect( url_for( '.view' ) )

        clz, formClz = None, UpdateForm
        if t == 'PT':
            clz, label = ProductType, u'商品类型'
        elif t == 'PS':
            clz, label = ProductShap, u'商品形状'
        elif t == 'PSR':
            clz, label = ProductSeries, u'商品系列'

        obj = clz.get( oid )
        form = formClz( request.form )
        form.name.data = obj.name
        form.remark.data = obj.remark
        return {'form' : form, 'obj' : obj, 'label' : label, 't' : t}


    @allPermission( ['MASTER_EDIT'] )
    @loginRequired
    def saveUpdate( self ):
        oid, t = _g( 'id' ), _g( 't' )
        if not oid or not t or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            if t :
                return redirect( url_for( '.view', action = 'pdtattr', t = t ) )
            else:
                return redirect( url_for( '.view' ) )

        clz, formClz = None, UpdateForm
        if t == 'PT':
            clz, label = ProductType, u'商品类型'
        elif t == 'PS':
            clz, label = ProductShap, u'商品形状'
        elif t == 'PSR':
            clz, label = ProductSeries, u'商品系列'
        try:
            obj = clz.get( oid )
            obj.update( _gld( 'name', 'remark' ) )
            db.commit()
            flash( MSG_UPDATE_SUCC, MESSAGE_INFO )
        except:
            traceback.print_exc()
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )

        return redirect( url_for( '.view', action = 'masindex', t = t ) )



    def delete( self ):
        oid, t = _g( 'id' ), _g( 't' )
        if not oid or not t or t not in ['PT', 'PS', 'PSR']:
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            if t :
                return redirect( url_for( '.view', action = 'masindex', t = t ) )
            else:
                return redirect( url_for( '.view' ) )


        if t == 'PT':
            clz = ProductType
        elif t == 'PS':
            clz = ProductShap
        elif t == 'PSR':
            clz = ProductSeries

        obj = clz.get( oid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( '.view', action = 'masindex', t = t ) )
        try:
            obj.active = INACTIVE
            obj.updateTime = dt.now()
            obj.updateById = getCurrentUserID()
            db.add( SysLog( refClz = clz.__name__, type = 'DELETE', refID = obj.id ) )
            db.commit()
            flash( MSG_DELETE_SUCC, MESSAGE_INFO )
        except:
            traceback.print_exc()
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
        return redirect( url_for( '.view', action = 'masindex', t = t ) )


    def _isDuplicate( self, dbclz, name ):
        try:
            qry( dbclz ).filter( dbclz.name == name ).one()
        except:
            return False
        else:
            flash( MSG_SAME_NAME_RECORD_EXIST, MESSAGE_ERROR )
            return True


bpMas.add_url_rule( '/', view_func = MasterView.as_view( 'view' ), defaults = {'action':'index'} )
bpMas.add_url_rule( '/<action>', view_func = MasterView.as_view( 'view' ) )




from wtforms import Form, TextField, TextAreaField, HiddenField

class SrhForm( Form ):
    t = HiddenField()
    no = TextField( u'系统编号', )
    name = TextField( u'名称', )
    createTimeFrom = MyDateField( u'创建时间(开始)', )
    createTimeTo = MyDateField( u'创建时间(结束)' )



class AddForm( Form ):
    t = HiddenField()
    name = TextField( u'名称', )
    remark = TextAreaField( u'备注', )


class UpdateForm( Form ):
    t = HiddenField()
    id = HiddenField()
    name = TextField( u'名称', )
    remark = TextAreaField( u'备注', )
